package com.jiangjiang.eshop.membership.biz;

import com.jiangjiang.eshop.membership.convert.UserAccountConvert;
import com.jiangjiang.eshop.membership.dto.UserAccountDTO;
import com.jiangjiang.eshop.membership.domain.UserAccountEntity;
import com.jiangjiang.eshop.membership.domain.UserDetailEntity;
import com.jiangjiang.eshop.membership.dto.PasswordUpdateDTO;
import com.jiangjiang.eshop.membership.dto.UserLoginDTO;
import com.jiangjiang.eshop.membership.service.UserAccountService;
import com.jiangjiang.eshop.membership.service.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @ClassName UserAccountBiz
 * @Description TODO
 * @Author jhw
 * @Date 2021/8/21 12:11
 * @Version 1.0
 **/
@Component
public class UserAccountBiz {
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private UserAccountConvert userAccountConvert;
    @Autowired
    private UserDetailService userDetailService;

    /**
     * 新增用户
     * @param dto 入参
     * @return 处理结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveUserAccount(UserAccountDTO dto){
        UserAccountEntity accountEntity = userAccountConvert.convertDOT2Entity(dto);
        userAccountService.save(accountEntity);

        // 保存用户账户明细数据
        UserDetailEntity userDetailEntity = new UserDetailEntity();
        userDetailEntity.setUserAccountId(accountEntity.getId());
        userDetailService.save(userDetailEntity);
        return true;
    }

    /**
     * 用户登录
     * @param dto 登录入参
     * @return 处理结果
     */
    public UserAccountDTO login(UserLoginDTO dto){
        // 现根据手机号查询
        UserAccountEntity userAccountEntity = userAccountService.queryByPhoneNumber(dto.getCellPhoneNumber());
        if(Objects.isNull(userAccountEntity)){
            throw new RuntimeException("账户不存在,请注册后再登录");
        }
        // 然后验证密码
        if(!userAccountEntity.getPassword().equals(dto.getPassword())){
            throw new RuntimeException("登录密码错误!!!");

        }
        return userAccountConvert.convertEntity2DTO(userAccountEntity);
    }

    /**
     * 根据用户id查询用户账户
     * @param id 用户id
     * @return 查询结果
     */
    public UserAccountDTO queryById(Long id){
        return userAccountConvert.convertEntity2DTO(userAccountService.getById(id));
    }


    /**
     * 更新密码
     * @param dto
     * @return
     */
    public Boolean updatePassword(PasswordUpdateDTO dto){
        return userAccountService.updatePassword(dto);
    }
}
